/*
 * @author Chris
 * @since 2023/1/25 16:09
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023-01-25     Chris        the first version
 */

#include "reg51.h"

__sbit cmdArrived = 0;  // 命令到达标志：1，已到达
unsigned int cmdIndex = 0;
unsigned char cntTxd = 0;
unsigned char *ptrTxd;

unsigned char array1[1] = {1};
unsigned char array2[2] = {1, 2};
unsigned char array3[4] = {1, 2, 3, 4};
unsigned char array4[8] = {1, 2, 3, 4, 5, 6, 7, 8};

void ConfigUART(unsigned long baud);

int main() {
    EA = 1;
    ConfigUART(9600);

    while (1) {
        if (cmdArrived) {
            cmdArrived = 0;
            switch (cmdIndex) {
                case 0x31:
                    ptrTxd = array1;        // 数组 1 的首地址赋值给发送指针
                    cntTxd = sizeof(array1);// 数组 1 的长度赋值给发送计数器
                    TI = 1;                 // 手动方式启动发送中断，处理数据发送
                    break;
                case 0x32:
                    ptrTxd = array2;
                    cntTxd = sizeof(array2);
                    TI = 1;
                    break;
                case 0x33:
                    ptrTxd = array3;
                    cntTxd = sizeof(array3);
                    TI = 1;
                    break;
                case 0x34:
                    ptrTxd = array4;
                    cntTxd = sizeof(array4);
                    TI = 1;
                    break;
                default:
                    break;
            }
        }
    }
}

void ConfigUART(unsigned long baud) {
    SCON |= 0x50;
    TMOD |= 0x20;
    TH1 = 256 - (11059200 / 12 / 2 / 16) / baud;
    TL1 = TH1;

    ET1 = 0;
    ES = 1;
    TR1 = 1;
}

/**
 * 串口中断服务函数
 */
void InterruptUART() __interrupt(4) {
    if (RI) {
        RI = 0;
        cmdIndex = SBUF;
        cmdArrived = 1;
    }

    if (TI) {
        TI = 0;
        if (cntTxd <= 0) {
            return;
        }

        SBUF = *ptrTxd;
        cntTxd--;
        ptrTxd++;
    }

}

